<!--下拉联动-->
<template>
	<el-cascader
		style="width: 100%"
		v-model="value"
		v-bind="allAttrs"
		:props="state.myProps"
		:clearable="clearable"
		:size="mySize"
		:options="myOptionList"
		:filter-method="filterMethod"
		:before-filter="beforeFilter"
		filterable
	>
	</el-cascader>
</template>

<script lang="ts" setup>
// 引入组件需要的属性 引入表单子控件的管理类
import { itemProps, itemController, shallowToDeep } from '../lib/mapController';
// 定义属性
const props = defineProps({
	...itemProps, // 基础属性
	optionKind: {
		type: String,
		default: 'deep', // deep 前端嵌套风格； shallow 后端浅层多数组风格
	},
	modelValue: [String, Number, Array],
	props: Object,
	url: String,
});
const attrs = useAttrs();
const emit = defineEmits(['update:modelValue']);
const allAttrs = computed(() => {
	return Object.assign(props.extend, attrs);
});
const state = reactive({
	mySize: allAttrs.value.size,
	myProps: Object.assign({value:'value',label:'label',children:'children',disabled:'disabled',leaf:'isLeaf'},props.props||{}) as any,
	myOptions: [] as any[],
});
const myOptionList = computed(() => {
	if (Array.isArray(props.options)) {
		// 数组类型
		// 没有数据
		if (props.options.length === 0) {
			return state.myOptions;
		} else {
			return props.options;
		}
	} else if (typeof props.options === 'object') {
		// 多表
		return shallowToDeep(props.options);
	}
	return [];
});
const { value, globalSize } = itemController(props, allAttrs.value, emit);
// 定义方法
const filterMethod = (node: any, value: any) => {
	if (props.props?.lazy) {
		return true;
	} else {
		return node.label.indexOf(value) >= 0;
	}
};
const beforeFilter = (value) => {
	return new Promise((resolve) => {
		if (props.props?.lazy) {
			let params = {
				lazy: false,
				searchText: value,
			};
			$http.post(props.url, params).then((res) => {
				if (props.props?.treeList) {
					let resList = res.result[props.props.treeList];
					state.myOptions = resList;
					resolve(true);
				}
			});
		} else {
			resolve(true);
		}
	});
};

const lazyLoad = (node, resolve) => {
	if (!props.url) {
		state.myProps.lazy = false;
	} else {
		if (node.root) {
			resolve(state.myOptions);
			return;
		}
		let params = {
			parentKey: node.value,
			lazy: true,
		};
		$http.post(props.url, params).then((res) => {
			let nodes: any[] = [];
			if (!props.props?.treeList) {
				resolve(nodes);
			} else {
				resolve(res.result[props.props.treeList]);
			}
		});
	}
};

// 初始化
globalSize(state);

if (!props.props?.lazyLoad) {
	state.myProps.lazyLoad = lazyLoad;
}


// 输出
const { mySize } = toRefs(state);
</script>
<script lang="ts">
// 声明额外的选项
export default {
	name: 'zh-cascader',
	inheritallAttrs: false,
};
</script>
